﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Windows.Storage;

namespace Books.Common
{
    public class IsoStoreHelper
    {
        public const string FileDownLoad = "filesDownload";
        public static async Task<bool> SaveObjectsAsync<T>(T sourceData, string targetFileName)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(targetFileName, CreationCollisionOption.ReplaceExisting);
            var outStream = await file.OpenStreamForWriteAsync();

            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(outStream, sourceData);
            await outStream.FlushAsync();
            outStream.Dispose();
            return true;
        }

        public static async Task<T> RestoreObjectsAsync<T>(string fileName)
        {
            var check = await FileExistsAsync(fileName);
            if (check)
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                var inStream = await file.OpenStreamForReadAsync();
                // Deserialize the objects. 
                DataContractSerializer serializer =
                    new DataContractSerializer(typeof(T));
                var data = (T)serializer.ReadObject(inStream);
                if (data != null)
                {
                    await inStream.FlushAsync();
                    return data;
                }
                else
                    await inStream.FlushAsync();
            }
            return default(T);

        }
        public static async Task<bool> FileExistsAsync(string fileName)
        {

            try
            {
                await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                return true;
            }
            catch (FileNotFoundException)
            {
                return false;
            }
        }
        public static async Task<bool> DeleteData()
        {
            var data = ApplicationData.Current;
            try
            {
                await data.ClearAsync();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}